package org.sanguine.study.hometasks.second;

import java.util.List;
import java.util.ListIterator;

public class Task12 {
	
	/**
	 * Reorder elements in list that elements less or equals X goes firstly then other goes. (O(n) complexity)
	 * @param list (must implements iterator.set operation otherwise UnsupportedOperationException throws)
	 * @param X - criteria of sorting
	 */
	
	public static void reoder(List<Integer> list, int X) {
		if (list == null || list.size() < 2) return;
		
		ListIterator<Integer> headIterator = list.listIterator();
		ListIterator<Integer> tailIterator = list.listIterator(1);
		
		while (tailIterator.hasNext()) {
			Integer leftValue = headIterator.next();
			Integer rightValue = tailIterator.next();
			
			if (leftValue <= X) continue;
			
			if (rightValue <= X) {
				headIterator.set(rightValue);
				tailIterator.set(leftValue);
				continue;
			}
			
			while (tailIterator.hasNext()) {
				rightValue = tailIterator.next();
				if (rightValue <= X) {
					headIterator.set(rightValue);
					tailIterator.set(leftValue);
					break;
				}
			}
		}
	}

}
